package com.anyonavinfo.cpaddemo.data.locationinfo.source.remote;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.anyonavinfo.cpaddemo.Application;
import com.anyonavinfo.cpaddemo.data.locationinfo.LocationInfo;
import com.anyonavinfo.cpaddemo.data.locationinfo.source.LocationInfoDataSource;
import com.anyonavinfo.cpaddemo.utils.okhttputils.CacheType;
import com.anyonavinfo.cpaddemo.utils.okhttputils.Callback;
import com.anyonavinfo.cpaddemo.utils.okhttputils.OKHttpUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by ZuiC on 2017/2/4.
 */

public class LocationInfoRemoteDataSource implements LocationInfoDataSource {

    private static LocationInfoRemoteDataSource INSTANCE = null;

    public static LocationInfoRemoteDataSource getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new LocationInfoRemoteDataSource();
        }
        return INSTANCE;
    }

    private LocationInfoRemoteDataSource(){

    }


    @Override
    public void getLocationInfo(double latitude, double longitude, final GetLocationInfoCallBack callBack) {
        final String uri = "http://maps.google.cn/maps/api/geocode/json?latlng="+latitude+","+longitude+"&sensor=true,language=zh-CN";
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder().url(uri).build();
                try {
                    Response execute = okHttpClient.newCall(request).execute();
                    if (execute.isSuccessful()) {
                        String location = execute.body().string();
                        if (location != null) {
                            LocationInfo locationInfo = new LocationInfo();
                            JSONObject jsonObject = new JSONObject(location);
                            JSONArray results = jsonObject.getJSONArray("results");
                            JSONObject jsonObject1 = results.getJSONObject(0);
                            JSONArray address_components = jsonObject1.getJSONArray("address_components");
                            JSONObject jsonObject2 = address_components.getJSONObject(3);
                            String long_name = jsonObject2.getString("long_name");
                            locationInfo.setCurCity(long_name);
                            callBack.onGetLocationInfo(locationInfo);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
